package com.muc.socket;

import com.muc.handler.MainViewHandlerToService;
import com.muc.view.MainView;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

public class MultiServerRunable implements Runnable{

    private Selector selector;
    SocketChannel socketChannel;
//    private MainView mainView;
    /*public MultiServerRunable(SelectionKey key) {
        this.key = key;
    }*/

    public MultiServerRunable(Selector open, SocketChannel socketChannel) {
        this.selector = open;
        this.socketChannel = socketChannel;
//        this.mainView = mainView;
    }

    @Override
    public void run() {
        try {
            socketChannel.configureBlocking(false);
            socketChannel.register(selector, SelectionKey.OP_READ);
            while (selector.select() > 0) {
                System.out.println("有关注事件发生,创建并启动子线程成功");
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    iterator.remove();
                    if (key.isReadable()) {
                        System.out.println("有可读事件发生,进行读取");
                        SocketChannel socketChannel = (SocketChannel) key.channel();
                        //创建buffer实例，一般创建1024大小
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        buffer.clear();
                        int count = 0;
                        StringBuilder s = new StringBuilder();
                        //使用缓冲区将客户端发送的数据提取完毕。
                        while ((count = socketChannel.read(buffer)) > 0) {
                            socketChannel.read(buffer);
                            System.out.println("循环接收");
                            buffer.flip();
                            byte[] bytes = new byte[buffer.remaining()];
                            buffer.get(bytes);
                            String msg = new String(bytes);
                            s.append(msg);
                            buffer.clear();
                            buffer.put(msg.getBytes());
                            buffer.flip();
                            socketChannel.write(buffer);
                            buffer.clear();
                        }
                        //打印信息提示读取的数据
                        System.out.println("本次传送读取到的数据是:");
                        System.out.println(s);
                        //关闭读写通道
                        if (count < 0) {
                            socketChannel.close();
                        }
                        //处理传递过来的数据
                        System.out.println("子线程传送数据");
                        /*try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }*/
                        new MainViewHandlerToService().caseByServiceInfo(s.toString());
                        System.out.println("子线程处理完数据");
                    }
                }
            }

        } catch (IOException e) {

        }
    }

        /*if (selector.isAcceptable()) {//ServerSocketChannel接收到一个连接
            ServerSocketChannel server = (ServerSocketChannel) key.channel();
            try {
                SocketChannel channel = server.accept();//接受请求
                channel.configureBlocking(false);
            } catch (IOException e) {
                e.printStackTrace();
            }

            //发送回复给客户
            channel.write(ByteBuffer.wrap(new String("Send Ack back to client...").getBytes()));
            //给Channel设置可读权限以继续接受请求
            channel.register(this.selector, SelectionKey.OP_READ );

        } else if (key.isReadable()) {//Channel进入读模式
            try {
                read(key);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public void read(SelectionKey key) throws IOException{
        SocketChannel channel = (SocketChannel) key.channel();//返回一个SocketChannel
        ByteBuffer buffer = ByteBuffer.allocate(50);
        channel.read(buffer);
        byte[] data = buffer.array();
        String msg = new String(data).trim();
        System.out.println("Server received msg："+msg);
        ByteBuffer outBuffer = ByteBuffer.wrap(msg.getBytes());
        channel.write(outBuffer);//读取客户传递的数据
    }*/

}
